package com.itheima.userdetailservice;


import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账户名称查询账户信息
        UserVO userVO = userService.findUserByUserName(username);

        //不存在用户 直接结束
        if (userVO==null){
            return null;
        }

       //走到这里表示数据库存在用户 直接获取角色列表
        Set<RoleVO> roles = userVO.getRoles();

        //封装权限表
        List<GrantedAuthority> authorities = new ArrayList<>();

        //根据角色查询权限
        for (RoleVO role : roles) {
                               //接口的实现类对象         //获取角色关键字
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));

            //获取权限关键字
            Set<Permission> permission = role.getPermission();

            for (Permission permission1 : permission) {
                authorities.add(new SimpleGrantedAuthority(permission1.getKeyword()));
            }

        }
        User user = new User(userVO.getUsername(),userVO.getPassword(),authorities);  //账号  密码 权限关键字


        return user;
    }
}
